/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.infrastructure.core.aspect.controller.children;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.hallele.infrastructure.metadata.constant.MsgCodeConst;
import cn.hallele.infrastructure.metadata.io.Response;
import cn.hallele.ms.infrastructure.core.aspect.controller.BaseExceptionAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/11/10 17:28
 */
@Slf4j
@Order(10)
@RestControllerAdvice
public class SaTokenExceptionAspect extends BaseExceptionAspect {
    /**
     * 拦截所有valid组件的 NotLoginException 的报错，
     *
     * @param e {@link NotLoginException}
     * @return 错误响应
     */
    @ExceptionHandler(NotLoginException.class)
    public Response<?> handleException(NotLoginException e) {
        String msgCode = MsgCodeConst.SESSION_INVALID;
        String msgDesc = i18n.getMessage(msgCode, new Object[]{}, getLocale());
        log.error("Find a NotLoginException. MsgCode: {}, msgDesc: {}.", msgCode, msgDesc, e);
        return buildResponse(msgCode, msgDesc);
    }

    /**
     * 拦截所有valid组件的 SaTokenException 的报错，
     *
     * @param e {@link SaTokenException}
     * @return 错误响应
     */
    @ExceptionHandler(SaTokenException.class)
    public Response<?> handleException(SaTokenException e) {
        String msgCode = MsgCodeConst.AUTHORIZATION_ERROR;
        String msgDesc = i18n.getMessage(msgCode, new Object[]{}, getLocale());
        log.error("Find a SaTokenException. MsgCode: {}, msgDesc: {}.", msgCode, msgDesc, e);
        return buildResponse(msgCode, msgDesc);
    }

    /**
     * 国际化
     *
     * @param i18n i18n
     */
    public SaTokenExceptionAspect(MessageSource i18n) {
        super(i18n);
    }
}
